<template>
  <div>
    <el-dialog v-model="state.showDialog" destroy-on-close :title="title" draggable :close-on-click-modal="false"
      :close-on-press-escape="false" width="569px">
      <el-form ref="formRef" :model="form" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="工站代号" :rules="[{ required: true, message: '请选中工站代号', trigger: ['blur', 'change'] }]">
              <el-select v-model="form.stationId" placeholder="请选中工站代号">
                <el-option v-for="item in state.stationTreeData" :key="item.id" :label="item.stationCode"
                  :value="item.id">
                  <span style="float: left">{{ item.stationCode }}</span>
                  <span style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;">
                    {{ item.stationName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="偏移量" :rules="[{ required: true, message: '请选中偏移量', trigger: ['blur', 'change'] }]">
              <el-select v-model="form.offsetId" placeholder="请选中偏移量" filterable>
                <el-option v-for="item in state.plcOffsetTreeData" :key="item.id" :label="item.byteOffset"
                  :value="item.id">
                  <span style="float: left">{{ item.byteOffset }}</span>
                  <span style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;">
                    {{ getDataTypeName(item.dataType) }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="参数名称" prop="paramKey"
              :rules="[{ required: false, message: '参数名称', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.paramKey" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="参数值" prop="paramValue"
              :rules="[{ required: false, message: '参数值', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.paramValue" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="排序" prop="sort"
              :rules="[{ required: false, message: '排序', trigger: ['blur', 'change'] }]">
              <el-input-number v-model="form.sort" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer my-flex my-flex-y-center my-flex-between">
          <div>
            <el-checkbox v-if="!(state.form?.id > 0)" v-model="state.contiAdd">连续新增</el-checkbox>
          </div>
          <div>
            <el-button @click="onCancel" size="default">取 消</el-button>
            <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="industry/route-detail/form">
import { reactive, toRefs, getCurrentInstance, ref, watch, computed } from 'vue'
import { FormulaDetailGetListOutput, FormulaDetailAddInput, FormulaDetailUpdateInput, WorkStationGetListOutput, PLCOffsetGetListOutput, PLCDataTypeEnum } from '/@/api/industry/data-contracts'
import { listToTree } from '/@/utils/tree'

import { FormulaDetailApi } from '/@/api/industry/FormulaDetail'
import { WorkStationApi } from '/@/api/industry/WorkStation'
import { PlcOffsetApi } from '/@/api/industry/PlcOffset'

import eventBus from '/@/utils/mitt'

defineProps({
  title: {
    type: String,
    default: '',
  },
})
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  expandRowKeys: [] as Number[],
  formulaDetailData: [] as FormulaDetailGetListOutput[],
  stationTreeData: [] as WorkStationGetListOutput[],
  plcOffsetTreeData: [] as PLCOffsetGetListOutput[],
  form: {} as FormulaDetailAddInput & FormulaDetailUpdateInput,
  contiAdd: false,

})
const { form } = toRefs(state)

const getDataTypeName = (type: any) => {
  const map = {
    0: 'BOOL',
    1: 'BYTE',
    2: 'WORD',
    3: 'DWORD',
    4: 'INT',
    5: 'DINT',
    6: 'REAL',
    7: 'LREAL',
    8: 'STRING'
  }
  return map[type] || type
}

// 打开对话框
const open = async (row: any = {}) => {
  state.contiAdd = false
  await getStations()
  await getPlcOffsets()
  if (row.id > 0) {
    const res = await new FormulaDetailApi().get({ id: row.id }, { loading: true }).catch(() => {
      proxy.$modal.closeLoading()
    })
    if (res?.success) {
      state.form = res.data as FormulaDetailAddInput & FormulaDetailUpdateInput
    }
  } else {
    state.form = { deviceFormulaId: row.deviceFormulaId } as FormulaDetailAddInput & FormulaDetailUpdateInput
  }
  state.showDialog = true
}
// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    state.sureLoading = true
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new FormulaDetailApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new FormulaDetailApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }
    state.sureLoading = false

    if (res?.success) {
      if (state.contiAdd) {
        formRef.value!.resetFields()
      }
      eventBus.emit('refreshFormulaDetail')
      state.showDialog = state.contiAdd
    }
  })
}

// 取消
const onCancel = () => {
  state.showDialog = false
}

const getStations = async () => {
  const res = await new WorkStationApi().getList({})
  if (res?.success && res.data && res.data.length > 0) {
    state.stationTreeData = listToTree(res.data) as WorkStationGetListOutput[]
  } else {
    state.stationTreeData = []
  }
}

const getPlcOffsets = async () => {
  const res = await new PlcOffsetApi().getList({})
  if (res?.success && res.data && res.data.length > 0) {
    state.plcOffsetTreeData = listToTree(res.data) as PLCOffsetGetListOutput[]
  } else {
    state.plcOffsetTreeData = []
  }
}
defineExpose({
  open,
})
</script>